﻿using System.Collections.ObjectModel;
using System.Collections.Specialized;
using Mss.Common.Helpers;

namespace Mss.Common.DomainObjects
{
    public class Validation : NotifyPropertyChangedBase
    {
        #region Fields

        private bool _isValid;

        #endregion

        #region Constructor

        public Validation()
        {
            Errors = new ObservableCollection<Error>();
            Errors.CollectionChanged += onErrorsCollectionChanged;
        }

        #endregion

        #region Properties

        public bool IsValid
        {
            get { return _isValid; }
            set
            {
                if (_isValid == value) return;
                _isValid = value;
                RaisePropertyChanged("IsValid");
            }
        }

        public ObservableCollection<Error> Errors { get; private set; }

        #endregion

        #region Methods

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        /// <filterpriority>2</filterpriority>
        public override void Dispose()
        {
            base.Dispose();

            foreach (var error in Errors)
            {
                error.Dispose();
            }

            Errors.CollectionChanged -= onErrorsCollectionChanged;
        }

        private void onErrorsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            IsValid = Errors.Count == 0;
        }

        #endregion
    }
}